import Taro from '@tarojs/taro';
import * as Sentry from '@bingo/sentry-taro';
import { Breadcrumbs } from '@bingo/sentry-taro/es/integrations';

class SentryReport {
  ISentryOptions;

  static instance: any;

  options: any;

  constructor(options) {
    this.options = options;
  }

  static getInstance(options) {
    if (!SentryReport.instance) {
      SentryReport.instance = new SentryReport(options);
      SentryReport.instance.initialize();
    }
    return SentryReport.instance;
  }

  initialize() {
    Sentry.init({
      dsn: this.options.dsn,
      release: this.options.release,
      environment: this.options.environment,
      // 仅在生产环境上报console
      integrations: [new Breadcrumbs({ console: this.options.environment === 'prod' })],
    });
    // 默认集成上报用户信息
    try {
      const user = Taro.getStorageSync('user');
      Sentry.setUser(user);
      Sentry.setTag('userName', user?.userName);
      Sentry.setTag('mobile', user?.phoneNumber);
    } catch (e) {
      this.reportException(e);
    }
  }

  /**
   * 手动上报异常信息
   * @param {*} errorInfo 异常信息
   */
  reportException(errorInfo) {
    Sentry.withScope((scope) => {
      Object.keys(errorInfo).forEach((key) => {
        if (key !== 'error') {
          scope.setExtra(key, errorInfo[key]);
        }
      });
      Sentry.captureException(errorInfo || new Error(''));
    });
  }

  /**
   * 手动上报请求失败信息
   * @param {msg} 失败原因
   * @param {requestOptions} 请求配置信息
   */
  reportRequestFail(msg = '', requestOptions = {}) {
    Sentry.withScope((scope) => {
      scope.setLevel(Sentry.Severity.Warning);
      scope.setExtra('requestData', requestOptions);
      Sentry.captureMessage(`RequestFail ${msg}`);
    });
  }
}

export default SentryReport;
